package com.sssre.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.sssre.business.domain.BusStatement;
import com.sssre.business.vo.BusStatementQueryParams;
import com.sssre.business.exception.ServiceValidException;
import com.sssre.business.mapper.BusStatementMapper;
import com.sssre.business.service.IBusStatementService;
import com.sssre.business.util.DateUtil;
import com.sssre.business.util.RegexUtils;
import com.sssre.business.util.VehiclePlateNoUtil;
import com.sssre.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 结算单Service业务层处理
 * 
 * @author 浪兎兎
 * @date 2025-04-29
 */
@Service
public class BusStatementServiceImpl implements IBusStatementService
{
    @Autowired
    private BusStatementMapper busStatementMapper;

    /**
     * 查询结算单
     * 
     * @param id 结算单主键
     * @return 结算单
     */
    @Override
    public BusStatement selectBusStatementById(Long id)
    {
        BusStatement busStatement = busStatementMapper.selectBusStatementById(id);
        if (busStatement == null)  throw new ServiceValidException("该数据不存在");
        if (Objects.equals(busStatement.getIsDelete(), BusStatement.DELETED)) throw new ServiceValidException("该数据已被删除");
        return busStatement;
    }

    /**
     * 查询结算单列表
     *
     * @param busStatement 结算单
     * @return 结算单
     */
    @Override
    public List<BusStatement> selectBusStatementList(BusStatement busStatement)
    {
        return busStatementMapper.selectBusStatementList(busStatement);
    }

    /**
     * 查询结算单列表
     *
     * @param busStatementQueryParams 结算单
     * @return 结算单
     */
    @Override
    public List<BusStatement> selectBusStatementList(BusStatementQueryParams busStatementQueryParams)
    {
        Date endTime = busStatementQueryParams.getEndTime();
        if (endTime != null) {
           busStatementQueryParams.setEndTime(DateUtil.getEndTime4Day(endTime));
        }
        return busStatementMapper.selectBusStatementListByTime(busStatementQueryParams);
    }

    /**
     * 新增结算单
     * 
     * @param busStatement 结算单
     * @return 结果
     */
    @Override
    public int insertBusStatement(BusStatement busStatement)
    {
        // 校验
        valid(busStatement);
        // 设置结算状态为结算中
        busStatement.setStatus(BusStatement.STATUS_CONSUME);
        // 设置创建时间
        busStatement.setCreateTime(DateUtils.getNowDate());
        // 设置预约单id为空
        busStatement.setAppointmentId(null);
        return busStatementMapper.insertBusStatement(busStatement);
    }

    /**
     * 基础校验
     *
     * @param busStatement 结算单
     * @return 结果
     */
    private void valid(BusStatement busStatement) {
        // 查询原始对象
        Long oldId = busStatement.getId();
        BusStatement old = busStatementMapper.selectBusStatementById(oldId);
        // 已经被删除的不能被操作
        if (old != null && old.getIsDelete().equals(BusStatement.DELETED)) {
            throw new ServiceValidException("该工单已被删除");
        }
        // 校验手机号合法性
        String customerPhone = busStatement.getCustomerPhone();
        if (!RegexUtils.isPhoneLegal(customerPhone)) {
            throw new ServiceValidException("手机号格式错误");
        }
        // 校验到店时间合法性
        Date actualArrivalTime = busStatement.getActualArrivalTime();
        if (actualArrivalTime.after(new Date())) {
            throw new ServiceValidException("到店时间必须在服务器当前时间之前");
        }
        // 校验车牌号合法性
        String licensePlate = busStatement.getLicensePlate();
        VehiclePlateNoUtil.VehiclePlateNoEnum vehiclePlateNo = VehiclePlateNoUtil.getVehiclePlateNo(licensePlate);
        if (vehiclePlateNo == null || vehiclePlateNo.ordinal() >= 7) {
            throw new ServiceValidException("车牌号格式错误");
        }
    }

    /**
     * 修改结算单
     * 
     * @param busStatement 结算单
     * @return 结果
     */
    @Override
    public int updateBusStatement(BusStatement busStatement)
    {
        // 校验
        valid(busStatement);
        // 已支付的工单是不能被修改的
        if (!BusStatement.STATUS_CONSUME.equals(busStatement.getStatus())) {
            throw new ServiceValidException("已支付的工单是不能被修改的");
        }
        return busStatementMapper.updateBusStatement(busStatement);
    }

    /**
     * 批量删除结算单
     * 
     * @param ids 需要删除的结算单主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementByIds(Long[] ids)
    {
        for (Long id : ids) {
            deleteValid(id);
        }
        return busStatementMapper.deleteBusStatementByIds(ids);
    }

    private void deleteValid(Long id) {
        // 查询原始对象
        BusStatement old = busStatementMapper.selectBusStatementById(id);
        // 已经被删除或已存在的的不能被操作
        if (old != null) {
            if (old.getIsDelete().equals(BusStatement.DELETED)) {
                throw new ServiceValidException("该工单已被删除");
            } else if (!old.getStatus().equals(BusStatement.STATUS_CONSUME)) {
                throw new ServiceValidException("已支付的结算单不能删除");
            }
        } else {
            throw new ServiceValidException("该工单不存在");
        }
    }

    /**
     * 删除结算单信息
     * 
     * @param id 结算单主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementById(Long id)
    {
        deleteValid(id);
        return busStatementMapper.deleteBusStatementById(id);
    }

    /**
     * 修改结算单优惠金额
     *
     * @param busStatement 结算单
     * @return 结果
     */
    @Override
    public int editDiscountAmount(BusStatement busStatement) {
        // 查询原始对象
        Long id = busStatement.getId();
        BusStatement old = busStatementMapper.selectBusStatementById(id);
        // 已经被删除或已存在的的不能被操作
        if (old != null) {
            if (old.getIsDelete().equals(BusStatement.DELETED)) {
                throw new ServiceValidException("该工单已被删除");
            } else if (!old.getStatus().equals(BusStatement.STATUS_CONSUME)) {
                throw new ServiceValidException("已支付的结算单不能被修改");
            }
            // 进行数据校验
        } else {
            throw new ServiceValidException("该工单不存在");
        }
        // 判断 折扣金额 是否大于 总金额
        BigDecimal discountAmount = busStatement.getDiscountAmount();
        BigDecimal totalAmount = old.getTotalAmount();
        if (totalAmount.max(discountAmount).equals(discountAmount)) {
            throw new ServiceValidException("折扣金额不能大于总金额");
        } else if (discountAmount.intValue() < 0) {
            throw new ServiceValidException("折扣金额不能小于0");
        }
        return busStatementMapper.editDiscountAmount(id, discountAmount);
    }
}
